//
//  ST_FinalST_PushPeculiarityViewController.swift
//  btvideo
//
//  Created by mac on 2020/1/13.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SwiftyUserDefaults
import SwifterSwift
import RealmSwift


//发布特质 最后一步-Controller
class ST_FinalST_PushPeculiarityViewController: ST_BTLightBarViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        set_up_right_btn()
        
        title_nav_btn.setTitleForAllStates("添加特质")
        
        view.addSubview(peculiarity_image_view)
        peculiarity_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(80)
            make.top.equalTo(own_navigation_bar.snp.bottom).offset(15)
            make.left.equalToSuperview().offset(15)
        }
        
        view.addSubview(peculiarity_title_label)
        peculiarity_title_label.snp.makeConstraints { (make) in
            make.top.equalTo(peculiarity_image_view).offset(5)
            make.left.equalTo(peculiarity_image_view.snp.right).offset(10)
        }
        
        
//        view.addSubview(right_image_view)
//        right_image_view.snp.makeConstraints { (make) in
//            make.top.equalTo(peculiarity_title_label)
//            make.left.equalTo(peculiarity_title_label.snp.right).offset(5)
//        }
        
        view.addSubview(type_label)
        type_label.snp.makeConstraints { (make) in
            make.top.equalTo(peculiarity_title_label.snp.bottom).offset(7)
            make.left.equalTo(peculiarity_title_label)
            make.height.equalTo(20)
            make.width.equalTo(50)
        }
        
        
        view.addSubview(love_number_btn)
        love_number_btn.snp.makeConstraints { (make) in
            make.top.equalTo(type_label.snp.bottom).offset(3)
            make.left.equalTo(peculiarity_title_label)
            make.height.equalTo(30)
            make.width.equalTo(100)
        }
        
        view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.top.equalTo(peculiarity_image_view.snp.bottom).offset(25)
            make.left.equalToSuperview().offset(27)
        }
        
        view.addSubview(text_view_container)
        text_view_container.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.top.equalTo(content_label.snp.bottom).offset(10)
            make.height.equalTo(102)
        }
        
        text_view_container.addSubview(textView)
        textView.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 15, left: 15, bottom: 7, right: 15))
        }
        
        text_view_container.addSubview(text_place_holder_label)
        
        text_place_holder_label.snp.makeConstraints { (make) in
            make.top.equalTo(textView).offset(7)
            make.left.equalTo(textView).offset(4)
            make.right.equalTo(textView)
        }
        
        text_view_container.addSubview(current_text_count_label)
        current_text_count_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-5)
            make.bottom.equalToSuperview().offset(-5)
        }
        
        
        view.addSubview(media_container)
        media_container.snp.makeConstraints { (make) in
            make.top.equalTo(text_view_container.snp.bottom).offset(20)
            make.left.equalToSuperview().offset(67)
            make.right.equalToSuperview().offset(-67)
            make.height.equalTo(media_container.snp.width).dividedBy(240.0/300.0)
        }
        
        media_container.addSubview(preview_image_view)
        preview_image_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        preview_image_view.addSubview(multi_images_view)
        multi_images_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(24)
            make.right.equalToSuperview().offset(-15)
            make.top.equalToSuperview().offset(15)
        }
        
        media_container.addSubview(browerBtn)
        browerBtn.snp.makeConstraints { (make) in
            make.edges.equalToSuperview()
        }
        
        
        view.addSubview(re_selected_btn)
        re_selected_btn.snp.makeConstraints { (make) in
            make.width.equalTo(140)
            make.height.equalTo(35)
            make.centerX.equalToSuperview()
            make.centerY.equalTo(media_container.snp.bottom)
        }
    
        
        bind_control_value()
     
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        add_notifications()
        
        bind_media_preview()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    
    fileprivate func set_up_right_btn(){
        
        right_nav_btn.setTitleForAllStates("发布")
        right_nav_btn.titleLabel?.font = UIFont.systemFont(ofSize: 15, weight: UIFont.Weight.semibold)
        right_nav_btn.backgroundColor = Color.init(hexString: "#FEC207")
        right_nav_btn.cornerRadius = 15
        right_nav_btn.snp.remakeConstraints { (make) in
            make.right.equalTo(own_navigation_bar).offset(-15)
            make.centerY.equalTo(title_nav_btn)
            make.width.equalTo(60)
            make.height.equalTo(30)
        }
        right_nav_btn.isHidden = false
        
    }
    
    fileprivate func bind_control_value(){
        
        guard let currModel = willPushPeculiarity else { return  }
        
        
        peculiarity_image_view.pin_setImage(from: currModel.image.compress_image().url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        
        peculiarity_title_label.text = currModel.name
        
        type_label.text = currModel.descriptionStr
        
        
        /**
                功能 #2950
                2.2.2-iOS-特质调整为以“组”的形式发布和查看
                (2.发布时的文字改为该组的文字描述，不再是“整个特质的标题”)
                
        if !currModel.remark.isEmpty{
            
            contentTextField.text = currModel.remark
            
            let w = currModel.remark.width(withConstrainedHeight: 100, font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium))
            
            sign_image_view.snp.updateConstraints { (make) in
                make.left.equalToSuperview().offset(28+5+w)
            }
            
        }*/
        
        
        type_label.snp.updateConstraints { (make) in
            make.width.equalTo(currModel.descriptionStr.width(withConstrainedHeight: 100, font:  UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)) + 22)
        }
        
        
        var text = currModel.like_num.st_number_description()+"个女生喜欢      "
        if let sex = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.sex , sex == .female{
            text = currModel.like_num.st_number_description()+"个男生喜欢      "
        }
        
        love_number_btn.setTitleForAllStates(text)
        
        let loveNumberBtnW = text.width(withConstrainedHeight: 100, font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)) + 22
        
        love_number_btn.snp.updateConstraints { (make) in
            make.width.equalTo(loveNumberBtnW)
        }
        
    }
    
    func bind_media_preview(){
        
        if let url = videoURL{
            
               self.stop()
               
               self.preview_image_view.isHidden = true
               
               self.play_video(pUrl: url)
               
        }else if let array = pictures, let img = array.first{
               
               self.stop()
               self.preview_image_view.image = img
               self.preview_image_view.isHidden = false
            
               self.multi_images_view.isHidden = array.count < 2
        }else{
            self.preview_image_view.isHidden = true
            self.multi_images_view.isHidden = true
            self.stop()
        }
    }
    
    
    
    
    //    MARK:- Outside Properties
    var videoLocalName:String?{
        didSet{
            
            if let videoName = videoLocalName,var base = SC.push_peculiarity_directory{
               
                base.appendPathComponent(videoName)
                
                videoURL = base
                
            }
        }
    }
    
    var videoURL:URL?
    
    var pictures:[UIImage]?

    //    MARK:- Properties
    fileprivate lazy var peculiarity_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        control.cornerRadius = 10
        return control
    }()
    
    
     fileprivate lazy var peculiarity_title_label:UILabel = {
        let control = UILabel.init()
        control.text = ""
        control.textColor = Color.init(hexString: "#333333")
//        control.numberOfLines = 0
//        control.textAlignment = .center
        control.font = UIFont.systemFont(ofSize: 20, weight: UIFont.Weight.semibold)
        return control
    }()
    
    fileprivate lazy var right_image_view:UIImageView = {
       let control = UIImageView()
        control.image = ST_ImageUtils.imageName("个人中心_icon_向后一页")
        return control
    }()
    
     fileprivate lazy var type_label:UILabel = {
         let control = UILabel.init()
         control.text = " "
         control.textColor = Color.init(hexString: "#61666F")
         control.backgroundColor = Color.init(hexString: "#F2F4F7")
         control.cornerRadius = 10
 //        control.numberOfLines = 0
         control.textAlignment = .center
         control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
         return control
     }()
    
    fileprivate lazy var love_number_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.white
        control.cornerRadius = 15
//        control.borderColor = Color.init(hexString: "#ED3E58")
//        control.borderWidth = 2
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 6, bottom: 0, right: 0)
//        control.setTitleForAllStates("来一起拍视频啦")
        control.setTitleColorForAllStates(UIColor.init(hexString: "#ED3E58")!)
        control.setImageForAllStates(ST_ImageUtils.imageName("首页_icon_X个喜欢")!)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var text_view_container:UIView = {
       let control = UIView()
        control.backgroundColor = Color.init(hexString: "#F5F8FA")
        control.cornerRadius = 15
        return control
    }()

    fileprivate lazy var textView:UITextView = {
       let control = UITextView()
        control.backgroundColor = .clear
        control.textColor = Color.init(hexString: "#61666F")
        control.tintColor = Color.init(hexString: "#61666F")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.delegate = self
        return control
    }()
    
    
    fileprivate let place_holder_attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular),.foregroundColor: UIColor(red: 0.67, green: 0.71, blue: 0.75, alpha: 1)]
    
    fileprivate lazy var normal_place_holder_string:NSAttributedString = {
        
        let attrString = NSMutableAttributedString(string: "认真描述自己的特质可以收获更多的赞和喜欢哦~")
        
         attrString.addAttributes(place_holder_attr, range: NSRange(location: 0, length: attrString.length))
        
        return attrString
    }()
    
    
    fileprivate lazy var text_place_holder_label:UILabel = {
       
        let control = UILabel()
      
        control.attributedText = normal_place_holder_string
        
        return control
    }()
    
    fileprivate lazy var current_text_count_label:UILabel = {
       
        let control = UILabel()
        control.textColor = UIColor.init(hex: 0xACB4C0)
        control.font = UIFont.systemFont(ofSize: 12)
        control.text = "0/\(maxCount)"
        return control
    }()

    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "##333333")
        control.text = "描述"
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate let maxCount = 100
    
    fileprivate lazy var media_container:UIView = {
        let control = UIView()
        control.backgroundColor = Color.white
//        control.backgroundColor = Color.random
        control.cornerRadius = 20
        return control
    }()
    
    
    fileprivate lazy var re_selected_btn:UIButton = {
            
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.setTitleForAllStates("重新选择")
        control.setTitleColorForAllStates(UIColor.white)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.backgroundColor = Color.init(hexString: "#FEC207")
        control.cornerRadius = 20
        control.add_touch_up(insideTarget: self, action: #selector(re_select_handle))
            return control
    }()
    
    fileprivate lazy var preview_image_view:UIImageView = {
       let control = UIImageView()
        control.contentMode = UIView.ContentMode.scaleAspectFill
        return control
    }()
    
    
    fileprivate lazy var multi_images_view:UIImageView = {
        let control = UIImageView.init(image: ST_ImageUtils.imageName("首页_icon_多图")!)
        control.isHidden = true
        return control
    }()
    
    fileprivate lazy var browerBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.add_touch_up(insideTarget: self, action: #selector(popupBrowerHandle))
        return control
    }()
    
    //    MARK: -  player properties
    //    播放中
    fileprivate var playing = false

    fileprivate var player:AVPlayer?

    fileprivate var time_observer:Any?

    fileprivate var playerItem:AVPlayerItem?

//    fileprivate var playerLayer:AVPlayerLayer?
    
    fileprivate var avPlayerView:ST_PairsAVPlayerView?
    
    fileprivate var currPalyIdx:Int?
    //    MARK: - Method
    override func left_click() {
        
        backEventHandle(ispop: true)
        
    }
    
    
    fileprivate func play_video(pUrl:URL) {
     
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
        }catch{
            print("AVAudioSession.Category.playback Error")
        }
        
        let playerItem = AVPlayerItem(url: pUrl)
        
        self.playerItem = playerItem

        //创建ACplayer：负责视频播放
        self.player = AVPlayer.init(playerItem: playerItem)
        self.player?.isMuted = true
        self.player?.rate = 1.0//播放速度 播放前设置
        //创建显示视频的图层
        
        
        avPlayerView = ST_PairsAVPlayerView()
        
        self.media_container.insertSubview(avPlayerView!, belowSubview: self.browerBtn)
        
//        avPlayerView?.backgroundColor = UIColor.red
        
        avPlayerView?.snp.makeConstraints({ (make) in
            make.edges.equalToSuperview()
        })
        
        guard let castedLayer = avPlayerView?.layer as? AVPlayerLayer else{
            return
        }
        
        castedLayer.player = self.player
        castedLayer.videoGravity = .resizeAspectFill
        
        guard let player = self.player else { return  }
        
        player.play()
        
        playing = true
        
    }
        
    fileprivate func stop(){
        
        playing = false
        
//        guard let playerLayer = self.playerLayer else { return  }
//        playerLayer.removeFromSuperlayer()
//        self.playerLayer = nil
        
        guard let player = self.player else { return  }
        
        if  let timerObs = self.time_observer{
            player.removeTimeObserver(timerObs)
        }
        
        avPlayerView?.removeFromSuperview()
        avPlayerView = nil
        
        player.pause()
        
        
        
        self.player = nil
    }
    
    fileprivate func save(image:UIImage)->String?{
        
        guard var path = SC.push_peculiarity_directory else { return nil }
        
        var writeData:Data?
        
        var filename = UUID().uuidString
        
//        if let data = try? image.heicData(compressionQuality: 0.8){
//
//            filename += ".heic"
//
//            path.appendPathComponent(filename)
//
//            writeData = data
//
//        }else if let data = image.jpegData(compressionQuality: 0.8) {
        
        if let data = image.jpegData(compressionQuality: SCComponets.asset_config.upload_compress_value.cgFloat) {
            
            filename += ".jpeg"
            
            path.appendPathComponent(filename)
            
            writeData = data
        }
        do {
            
            guard let d = writeData else { return nil }
            
            try d.write(to: path)
            
        } catch {
            print("error saving file to documents:", error)
            return nil
        }
        
        return filename
        
    }
    
    override func right_click() {
        
        
        ST_BTUserInfoManager.shared.judge_account_frozen().withUnretained(self).subscribe(onNext: { own,_ in
            
                own.startPush()
            
        }).disposed(by: rx.disposeBag)
        
    }
    
    private func startPush(){
        
        
        if BTVerticalAlertViewController.toastBindPhoneRequireAlert(fromController: self) {
            return
        }
        
        guard let remark = textView.text , remark.isEmpty == false else{
            
            ToastHud(text: "必须填写特质描述哦", view: self.view)
            
            return
        }
        
        guard let detail = willPushPeculiarity else { return  }
        
        let task = ST_PushPeculiarityTask()
        task.peculiarity_id = detail.id.string
        task.peculiarityName = detail.name
        task.accountId = Defaults[.currentUserID]
//        if let str = contentTextField.text{
            task.remark = remark
//        }
        
        if let url = videoURL{
            
            task.videoPath = url.path
            
            guard let img = url.get_video_thumbnail_image(),let imgPath = save(image: img) else{
                return
            }
            
            let duration = AVURLAsset(url: url).duration.seconds
            
            task.coverImagePath = imgPath
            
            task.imageWidth = img.size.width.double
            
            task.imageHeight = img.size.height.double
            
            task.videoDuration = duration.int
            
            self.finalStep(task: task)
            
        }else if let imageArray = pictures{
            
            
            for (idx,img) in imageArray.enumerated() {
                
                let imgPath = img.compress_with_cache_s_d_image()
                
                let resource = ST_PushPeculiarityTaskResource()
                
                resource.taskId = task.id
                
                resource.path = imgPath
                
                resource.imageWidth = img.size.width.double
                
                resource.imageHeight = img.size.height.double
                
                resource.sortInTask = idx
                
                task.resources.append(resource)
            }
            
            task.resources.forEach({$0.taskResourceCount = task.resources.count })
            
            self.finalStep(task: task)
        }

    }
    
    
    fileprivate func finalStep(task:ST_PushPeculiarityTask){
        
        let realm = try! Realm()
        
        try! realm.write {
            realm.add(task)
        }
        
        ST_PushPeculiarityCoordinator.shared.task_loop()
        
        UIView.animate(withDuration: 0, animations: {
            self.navigationController?.popToRootViewController(animated: true)
        }) { (f) in
            
            UIApplication.shared.tainMainWindow?.rootViewController?.dismiss(animated: true) {
                ST_BTLaunchController.shared.scroll_to_page(tab: .recommend)
            }
        }
        
    }
    
}


//MARK:- Event
extension ST_FinalST_PushPeculiarityViewController{
    
    @objc func re_select_handle(){
        
        backEventHandle()
        
        
    }
    
    @objc fileprivate func popupBrowerHandle(){
        
        if let data = pictures,data.count > 0{
            previewPicures(data_array: data)
        }
        
        if let  url = videoURL{
            
            
            let playCtr = ST_BTPlayerViewController()
            
            playCtr.show_delete_action = false
            
            playCtr.type = .localUrl
            
            playCtr.videoUrl = url.path
            
            GlobalPresent(toController: playCtr)
            
        }
        
        
    }
    
    fileprivate func previewPicures(data_array:[UIImage]){
        
               
       var array = [ST_MWPhoto]()
       
       for model in data_array{
           
           guard let media = ST_MWPhoto.init(image: model) else{
               continue
           }
           array.append(media)
       }
       
       guard let browser = ST_MWPhotoBrowser.init(photos: array) else{
           return
       }
       browser.displayActionButton = false;
       browser.setCurrentPhotoIndex(0)
       
       let nav = UINavigationController.init(rootViewController: browser)
       
       GlobalPresent(toController: nav)
        
    }
    
    fileprivate func backEventHandle(ispop:Bool = false){
        
        
        let attrString = NSMutableAttributedString(string: "提示")
        
           let attr: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 18, weight: UIFont.Weight.medium),.foregroundColor: UIColor(red: 0.2, green: 0.2, blue: 0.2, alpha: 1)]
           attrString.addAttributes(attr, range: NSRange(location: 0, length: attrString.length))
           
           let attrString1 = NSMutableAttributedString(string: "现在返回会丢失已有内容，\n是否确定重新编辑？")
           
           let paragh = NSMutableParagraphStyle()
           paragh.alignment = .center
           
           let attr1: [NSAttributedString.Key : Any] = [.font: UIFont.systemFont(ofSize: 14),.foregroundColor: UIColor(red: 0.4, green: 0.4, blue: 0.4, alpha: 1),.paragraphStyle:paragh]
           
           attrString1.addAttributes(attr1, range: NSRange(location: 0, length: attrString1.length))
           
           
           let alert = BTVerticalAlertViewController.init(title: attrString, message: attrString1, imageName: "首页_icon_提示", confirmText: "重新编辑", cancelText: "取消")

           alert.overCurrentContext = true
           
           alert.over_current_context_alpha = "0.4"

           alert.root_view_height = 290
           
           alert.root_view_width = 250
        
            alert.confirm_closure = { [weak self] in
                
                
                self?.stop()
                self?.videoURL = nil
                self?.pictures = nil
                
                self?.bind_media_preview()
                
                if ispop{
                    
                    self?.goback_previous_controller()
                    
                }else{
                    
                    
                    let vc = ST_JVImagePickerController()
                    
                    vc.overCurrentContext = true
                    
                    vc.picker_images_closure = {[weak self] images in
                        
                        self?.pictures = images.map({ (id,img) -> UIImage in
                            return img
                        })
                        
                        self?.bind_media_preview()
                    }
                    
                    vc.picker_video_closure = {[weak self] url,seconds in
                        
                        let filename = UUID().uuidString+".mp4"
                        
                        guard var videoPath = SC.push_peculiarity_directory else { return }
                        
                        videoPath.appendPathComponent(filename)
                        
                        do {
                            try FileManager.default.copyItem(at: url, to: videoPath)
                        } catch (let error) {
                            print("Cannot copy item at \(url) to \(videoPath): \(error)")
                            return
                        }
                        
                        self?.videoURL = videoPath
                        
                        self?.bind_media_preview()
                        
                    }
                    
                    GlobalPresent(toController: vc)
                }
                
            }
           
           GlobalPresent(toController: alert)
        
    }
    
}

extension ST_FinalST_PushPeculiarityViewController:UITextViewDelegate{
    
    func textViewDidChange(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textViewDidBeginEditing(_ textView: UITextView) {
        text_place_holder_label.isHidden = !textView.text.isEmpty
    }
    
    func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
        
        guard var animal = textView.text else{
            return true
        }
        
        if let idxRange = Range.init(range, in: animal){
            
            animal.replaceSubrange(idxRange, with: text)
            
            var residueCount = maxCount - animal.count
            
            if residueCount < 0{
                residueCount = 0
            }
            
            var displayCount = animal.count
            
            if displayCount > maxCount{
                displayCount = maxCount
            }
            
            current_text_count_label.text = "\(displayCount)/\(maxCount)"
            
            return animal.count <= maxCount
            
        }else{
            return true
        }
    }
    
}


//MARK: - Notification
extension ST_FinalST_PushPeculiarityViewController{
    
    
    func add_notifications()  {
            
        NotificationCenter.default.addObserver(forName: .AVPlayerItemDidPlayToEndTime, object: self.player?.currentItem, queue: .main) { [weak self] noti in
            
            if let playerItem = noti.object as? AVPlayerItem{
                
                if let currentItem = self?.player?.currentItem,playerItem == currentItem{
                    
//                    print("FWPlayer---播放完成，重新播放")
                    
                    self?.player?.seek(to: CMTime.zero)
                    self?.player?.play()
                    
                    return
                }
            }
        }
        
    }
}
